import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:wu_you/data/cache/username_password_cache.dart';
import 'package:wu_you/data/db/dao/login_history_dao.dart';
import 'package:wu_you/data/repository/auth_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/user_model.dart';
import 'package:wu_you/page/page_main.dart';
import 'package:wu_you/page/splash/page_forget_psw.dart';
import 'package:wu_you/page/splash/page_reg.dart';
import 'package:wu_you/page/user/page_setting.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/utils/error_handler.dart';
import 'package:wu_you/utils/login_util.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/http_status_button.dart';
import 'package:toast/toast.dart';
import 'package:wu_you/utils/extension_utils.dart';

//登录
class LoginPage extends StatefulWidget{
  @override
  LoginPageState createState() => LoginPageState();
}
class LoginPageState extends State<LoginPage>{
  final _formKey = GlobalKey<FormState>();
  TextEditingController _usernameController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  TapGestureRecognizer _userProtocolRecognizer = TapGestureRecognizer();
  TapGestureRecognizer _privacyProtocolRecognizer = TapGestureRecognizer();
  FocusNode _focusNode = FocusNode();
  ButtonStatusController _controller;
  final FocusNode _verifyNode = FocusNode();
  bool showPwd = false;
  bool _isAgree = false;
  var message;


  @override
  void initState() {
    super.initState();
    _userProtocolRecognizer.onTap = () {

    };
    _privacyProtocolRecognizer.onTap = () {

    };
    UsernamePasswordCache cache = UsernamePasswordCache();
    cache.getArray().then((value) {
      _usernameController.text = value[0];
      _passwordController.text = value[1];
    });

  }



  List<UserPsw> loginUserList = [];


  Widget buildAutoComplete() {
    return Autocomplete<UserPsw>(
      optionsBuilder: buildOptions,
      optionsViewBuilder: _buildOptionsView,
      fieldViewBuilder: _buildFieldView,
      displayStringForOption: (user) => user.username,
    );
  }
  Future<Iterable<UserPsw>> buildOptions(TextEditingValue textEditingValue) async {
    // if (textEditingValue.text == '') {
    //   return const Iterable<UserPsw>.empty();
    // }
    return searchByArgs(textEditingValue.text);
  }
  Future<Iterable<UserPsw>> searchByArgs(String args) async {
    await Future.delayed(const Duration(milliseconds: 200));
    loginUserList.clear();
    List<UserPsw> user = await LoginHistoryDao().getAll();
    loginUserList.addAll(user);
    return loginUserList.where((UserPsw user) => user.username.contains(args));
  }
  Widget _buildOptionsView(BuildContext context, AutocompleteOnSelected<UserPsw> onSelected, Iterable<UserPsw> options) {
    return Align(
      alignment: Alignment.topLeft,
      child: Padding(
        padding: EdgeInsets.zero,
        child: Material(
          child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 150.0,maxWidth: 220),
              child: ListView.separated(
                  padding: EdgeInsets.zero,
                  itemBuilder: (context,index){
                    UserPsw option = options.elementAt(index);
                    return Container(
                      height: 45,
                      alignment: Alignment.centerLeft,
                      padding: EdgeInsets.only(left: 6,right: 6),
                      child: Text.rich(formSpan(option.username, _usernameController.text)),
                    ).addGesture(() {
                      onSelected.call(option);
                      _passwordController.text = option.password;
                    });
                  },
                  separatorBuilder: (context,index){
                    return Divider();
                  },
                  itemCount: options .length
              )
          ),
        ),
      ),
    );
  }
  ///高亮某些文字
  final TextStyle lightTextStyle = const TextStyle(
    color: Colors.blue,
    fontWeight: FontWeight.bold,
  );
  InlineSpan formSpan(String src, String pattern) {
    List<TextSpan> span = [];
    List<String> parts = src.split(pattern);
    if (parts.length > 1) {
      for (int i = 0; i < parts.length; i++) {
        span.add(TextSpan(text: parts[i]));
        if (i != parts.length - 1) {
          span.add(TextSpan(text: pattern, style: lightTextStyle));
        }
      }
    } else {
      span.add(TextSpan(text: src));
    }
    return TextSpan(children: span,style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold));
  }

  Widget _buildFieldView(
      BuildContext context,
      TextEditingController textEditingController,
      FocusNode focusNode,
      VoidCallback onFieldSubmitted) {
    _usernameController = textEditingController;
    _focusNode = focusNode;
    return SizedBox(
      height: 45,
      child: TextFormField(
        style: TextStyle(fontSize: 15,color: AppColors.textColor),
        maxLines: 1,
        textAlignVertical: TextAlignVertical.center,
        textInputAction: TextInputAction.next,
        controller: textEditingController,
        keyboardType: TextInputType.text,
        autofocus: false,
        focusNode: focusNode,
        cursorColor: Theme.of(context).primaryColor,
        validator: (value) {
          return value.length == 0 ? '${message['enterAccount']}' : null;
        },
        onFieldSubmitted: (String value) {
          onFieldSubmitted();
        },
        textAlign: TextAlign.start,
        decoration: InputDecoration(
          suffixIcon: IconButton(
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            constraints: BoxConstraints.loose(Size(24, 24)),
            iconSize: 18,
            icon: Icon(Icons.close_rounded),
            onPressed: () {
              _usernameController.clear();
            },
          ),
          border: UnderlineInputBorder(
            borderSide: BorderSide.none,
          ),
          errorMaxLines: 1,
          counterText: '',
          contentPadding: EdgeInsets.only(left: 10),
          hintText: "${message['enterAccount']}",
          hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
        ),
      ),
    );
  }


  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("${message['login']}"),
        // actions: [
        //   TextButton(onPressed: (){
        //     NavigatorUtil.navigateToPage(context, SelectLanguagePage());
        //   }, child: Text("${message['langChange']}",style: TextStyle(color: Colors.white),)).addPadding(EdgeInsets.only(right: 6))
        // ],
      ),
      body: Padding(
        padding:const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(bottom: 40),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(8),
                        child: Image.asset(
                          Utils.getImgPath('ic_logo'),
                          height: 64,
                          width: 64,
                        ),
                      ),
                      SizedBox(height: 15,),
                      Text("${message['welcome']}",style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),)
                    ],
                  )
                ),

                Padding(padding: EdgeInsets.only(left: 20,right: 20),
                  child: Column(
                    children: [

                      buildAutoComplete(),
                      // TextFormField(
                      //   style: TextStyle(fontSize: 15,color: AppColors.textColor),
                      //   maxLines: 1,
                      //   textAlignVertical: TextAlignVertical.center,
                      //   textInputAction: TextInputAction.next,
                      //   controller: _usernameController,
                      //   keyboardType: TextInputType.text,
                      //   autofocus: false,
                      //   cursorColor: Theme.of(context).primaryColor,
                      //   validator: (value) {
                      //     return value.length == 0 ? '${message['enterAccount']}' : null;
                      //   },
                      //   textAlign: TextAlign.start,
                      //   decoration: InputDecoration(
                      //     suffixIcon: IconButton(
                      //       splashColor: Colors.transparent,
                      //       highlightColor: Colors.transparent,
                      //       constraints: BoxConstraints.loose(Size(24, 24)),
                      //       iconSize: 18,
                      //       icon: Icon(Icons.close_rounded),
                      //       onPressed: () {
                      //         _usernameController.clear();
                      //       },
                      //     ),
                      //     border: UnderlineInputBorder(
                      //       borderSide: BorderSide.none,
                      //     ),
                      //     errorMaxLines: 1,
                      //     counterText: '',
                      //     contentPadding: EdgeInsets.only(left: 10),
                      //     hintText: "${message['enterAccount']}",
                      //     hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                      //   ),
                      // ),
                      Divider(
                        height: 2,
                        color: HexColor("#EAEAEA"),
                      ),
                      TextFormField(
                        style: TextStyle(fontSize: 15,color: AppColors.textColor),
                        maxLines: 1,
                        controller: _passwordController,
                        textAlignVertical: TextAlignVertical.center,
                        textInputAction: TextInputAction.done,
                        maxLength: 16,
                        keyboardType: TextInputType.text,
                        autofocus: false,
                        focusNode: _verifyNode,
                        obscureText: showPwd ? false : true,
                        cursorColor: Theme.of(context).primaryColor,
                        validator: (value) {
                          return value.length == 0 ? '${message['enterPwd']}' : null;
                        },
                        textAlign: TextAlign.start,
                        decoration: InputDecoration(
                          fillColor: Colors.white,
                          filled: true,
                          border: UnderlineInputBorder(
                            borderSide: BorderSide.none,
                            // borderRadius: const BorderRadius.all(Radius.circular(24)),
                          ),
                          suffixIcon: IconButton(
                            splashColor: Colors.transparent,
                            highlightColor: Colors.transparent,
                            constraints: BoxConstraints.loose(Size(24, 24)),
                            iconSize: 18,
                            icon: Image.asset(showPwd ? Utils.getImgPath('ic_password_yes') : Utils.getImgPath('ic_password_no'),width: 18,height: 18,),
                            onPressed: () {
                              showPwd = !showPwd;
                              setState(() {});
                            },
                          ),
                          prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                          errorMaxLines: 1,
                          counterText: '',
                          contentPadding: EdgeInsets.only(left: 10),
                          hintText: "${message['enterPwd']}",
                          hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                        ),
                      ),
                      Divider(thickness: 1,),

                      SizedBox(height: 18,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          GestureDetector(
                            child: Icon(
                              _isAgree ? Icons.check_circle : Icons.panorama_fish_eye,
                              size: 19,
                              color: _isAgree
                                  ? AppColors.primaryColor
                                  : AppColors.textHintColor,
                            ),
                            onTap: (){
                              setState(() {
                                _isAgree = !_isAgree;
                              });
                            },
                          ),
                          SizedBox(width: 1,),
                          Expanded(child: Text.rich(
                              TextSpan(
                                children: [
                                  TextSpan(
                                    text: "${message['loginLable']}",
                                    style: TextStyle(color: AppColors.textHintColor, fontSize: 13),
                                  ),
                                  TextSpan(
                                    text: "《${message['userAgreement']}》",
                                    style: TextStyle(color: AppColors.textColor, fontSize: 13,fontWeight: FontWeight.bold),
                                    recognizer: _userProtocolRecognizer,
                                  ),
                                  TextSpan(
                                    text: "《${message['privacyAgreement']}》",
                                    style: TextStyle(color: AppColors.textColor, fontSize: 13,fontWeight: FontWeight.bold),
                                    recognizer: _privacyProtocolRecognizer,
                                  ),
                                ],
                              ),
                              maxLines: 2,
                            ),
                          )
                        ],
                      ),

                      SizedBox(height: 18,),
                      SizedBox(
                        width: double.infinity,
                        height: 42,
                        child: StatusButton(
                          none: Text("${message['login']}"),
                          stateController: (controller) {
                            _controller = controller;
                            _controller.stream.listen((state) {
                              switch (state) {
                                case ButtonStatus.none:
                                  break;
                                case ButtonStatus.loading:
                                  _onLogin();
                                  break;
                                case ButtonStatus.done:
                                  _navigateToMainPage();
                                  break;
                              }
                            });
                          },
                          done: Text("${message['loginSuccess']}"),
                          style: ButtonStyle(
                            shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
                          ),
                        ),
                      ),

                      SizedBox(height: 20,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("${message['forgetPsw']}?",style: TextStyle(fontSize: 15,color: AppColors.primaryColor),).addGesture(() {
                            NavigatorUtil.navigateToPage(context, ForgetPwdPage());
                          }),
                          Text("${message['register1']}",style: TextStyle(fontSize: 15,color: AppColors.primaryColor)).addGesture(() {
                            NavigatorUtil.navigateToPage(context, RegPage());
                          })
                        ],
                      )

                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      )
    );
  }

  void _onLogin() {
    var _state = _formKey.currentState;
    if (_state == null) {
      _controller?.value = ButtonStatus.none;
      return;
    }
    if (!_state.validate()) {
      _controller?.value = ButtonStatus.none;
      return;
    }
    if (!_isAgree) {
      _controller?.value = ButtonStatus.none;
      Toast.show("${message['qxtyxy']}", context);
      return;
    }
    _verifyNode.unfocus();
    var username = _usernameController.text;
    var password = _passwordController.text;
    AuthRepository().login(username, password).then((value)async {
      LoginUtil.initGlobalInfo(context);

      ///保存登录对象账号
      await LoginHistoryDao().insert(username, password).then((value){
        _controller?.value = ButtonStatus.done;
      },onError: (e){
        _controller?.value = ButtonStatus.done;
      });
    }).catchError((error) {
      ErrorHandler.handleError(error, action: (msg) {
        _controller?.value = ButtonStatus.none;
        Toast.show("$msg", context);
      });
    });
  }


  void _navigateToMainPage() {
    Navigator.pushAndRemoveUntil(
      this.context,
      MaterialPageRoute(
        builder: (context) => MainPage(),
      ),
          (route) => false,
    );
  }
}